<template>
  <div class="step-one">
    <Header :active-step="currentStep"/>
    <div class="form-container">
      <div class="form-card">
        <div class="form-header">
          <el-button
            icon="el-icon-arrow-left"
            class="back-button"
            type="text"
            @click="goBack"
          >
            返回首页
          </el-button>
          <h2 class="form-title">商家认证信息</h2>
        </div>

        <!-- 添加状态提示 -->
        <div v-if="certificationStatus" class="status-alert">
          <el-alert
            :title="certificationStatus.title"
            :type="certificationStatus.type"
            :description="certificationStatus.description"
            show-icon
            :closable="false"
            style="margin-bottom: 20px;"
          >
          </el-alert>
        </div>

        <el-form
          :model="form"
          :rules="rules"
          ref="form"
          label-width="160px"
          class="auth-form"
        >
          <!-- 商家名称 -->
          <!-- <el-form-item label="商家名称" prop="merchantName">
            <el-input
              v-model="form.merchantName"
              placeholder="请输入商家名称"
              prefix-icon="el-icon-office-building"
            ></el-input>
          </el-form-item> -->

          <!-- 联系人 -->
          <!-- <el-form-item label="联系人" prop="contactName">
            <el-input
              v-model="form.contactName"
              placeholder="请输入联系人姓名"
              prefix-icon="el-icon-user"
            ></el-input>
          </el-form-item> -->

          <!-- 联系电话 -->
          <!-- <el-form-item label="联系电话" prop="contactPhone">
            <el-input
              v-model="form.contactPhone"
              placeholder="请输入联系电话"
              prefix-icon="el-icon-phone"
            ></el-input>
          </el-form-item> -->

          <!-- 商家地址 -->
          <!-- <el-form-item label="商家地址" prop="address">
            <el-input
              v-model="form.address"
              placeholder="请输入详细地址"
              prefix-icon="el-icon-location"
            ></el-input>
          </el-form-item> -->

          <!-- 身份证正面上传 -->
          <el-form-item label="身份证正面" prop="idCardFront">
            <div class="upload-container">
              <upload-image
                :value="form.idCardFront"
                :limit="1"
                :fileSize="5"
                :fileType="['png', 'jpg', 'jpeg']"
                @input="value => form.idCardFront = value"
              />
              <div class="upload-tip">
                <i class="el-icon-info"></i>
                支持jpg、png格式，大小不超过5M
              </div>
            </div>
          </el-form-item>

          <!-- 身份证反面上传 -->
          <el-form-item label="身份证反面" prop="idCardBack">
            <div class="upload-container">
              <upload-image
                :value="form.idCardBack"
                :limit="1"
                :fileSize="5"
                :fileType="['png', 'jpg', 'jpeg']"
                @input="value => form.idCardBack = value"
              />
              <div class="upload-tip">
                <i class="el-icon-info"></i>
                支持jpg、png格式，大小不超过5M
              </div>
            </div>
          </el-form-item>

          <!-- 营业执照上传 -->
          <el-form-item label="营业执照" prop="businessLicense">
            <div class="upload-container">
              <upload-image
                :value="form.businessLicense"
                :limit="1"
                :fileSize="5"
                :fileType="['png', 'jpg', 'jpeg', 'pdf']"
                @input="value => form.businessLicense = value"
              />
              <div class="upload-tip">
                <i class="el-icon-info"></i>
                支持jpg、png、pdf格式，大小不超过5M
              </div>
            </div>
          </el-form-item>
<!--          供应商类型认证-->
          <el-form-item
            label="供应商类型"
            prop="roleKey"
            v-if="userType === 'supplier'"
          >
            <el-select
              v-model="form.roleKey"
              placeholder="请选择供应商类型"
              style="width: 100%"
            >
              <el-option
                v-for="role in supplizerRoleList"
                :key="role.key"
                :label="role.label"
                :value="role.key"
              >
                <span>{{ role.label }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">
                  {{ role.description }}
                </span>
              </el-option>
            </el-select>
            <div class="select-tip">
              <i class="el-icon-info"></i>
              请选择您的供应商类型，不同类型有不同的权限和服务
            </div>
          </el-form-item>
          <!-- 添加采购商角色选择 -->
          <el-form-item
            label="采购商类型"
            prop="roleKey"
            v-if="userType === 'purchaser'"
          >
            <el-select
              v-model="form.roleKey"
              placeholder="请选择采购商类型"
              style="width: 100%"
            >
              <el-option
                v-for="role in purchaserRoleList"
                :key="role.key"
                :label="role.label"
                :value="role.key"
              >
                <span>{{ role.label }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">
                  {{ role.description }}
                </span>
              </el-option>
            </el-select>
            <div class="select-tip">
              <i class="el-icon-info"></i>
              请选择您的采购商类型，不同类型有不同的权限和服务
            </div>
          </el-form-item>
        </el-form>
        <!--此处如果角色为采购商，判断申请：purchaser-retail（采购商普通散户）还是purchaser-stratagem（采购商-战略合作商）还是purchaser-guarantor（采购商-担保合作商）-->


        <div class="form-footer">
          <div class="agreement">
            <el-checkbox v-model="agree">我已阅读并同意</el-checkbox>
            <el-link type="primary" class="agreement-link">《平台供应商注册协议》</el-link>
            <span>及</span>
            <el-link type="primary" class="agreement-link">《平台隐私政策》</el-link>
          </div>

          <div class="button-group">
            <el-button
              type="primary"
              class="submit-button"
              @click="submit"
              :disabled="!agree"
              :loading="submitting"
            >
              提交认证
            </el-button>

            <el-button
              type="info"
              class="view-button"
              @click="getCertificationResult"
              plain
            >
              查看认证记录
            </el-button>
          </div>
        </div>
      </div>

      <!-- 认证记录卡片 -->
      <el-dialog
        title="认证记录"
        :visible.sync="showResult"
        width="50%"
        class="result-dialog"
      >
        <div v-if="certificationResult" class="result-content">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="认证状态">
              <el-tag :type="getStatusType">{{ getStatusText }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="商家名称">
              {{ certificationResult.merchantName }}
            </el-descriptions-item>
            <el-descriptions-item label="联系人">
              {{ certificationResult.contactName }}
            </el-descriptions-item>
            <el-descriptions-item label="联系电话">
              {{ certificationResult.contactPhone }}
            </el-descriptions-item>
            <el-descriptions-item label="商家地址">
              {{ certificationResult.address }}
            </el-descriptions-item>
            <el-descriptions-item label="审核原因" v-if="certificationResult.reason">
              {{ certificationResult.reason }}
            </el-descriptions-item>
          </el-descriptions>

          <div class="image-preview">
            <div class="preview-item" v-if="certificationResult.idCardFront">
              <h4>身份证正面</h4>
              <el-image
                :src="certificationResult.idCardRight"
                fit="cover"
                :preview-src-list="[certificationResult.idCardRight]"
              ></el-image>
            </div>
            <div class="preview-item" v-if="certificationResult.idCardBack">
              <h4>身份证反面</h4>
              <el-image
                :src="certificationResult.idCardBack"
                fit="cover"
                :preview-src-list="[certificationResult.idCardBack]"
              ></el-image>
            </div>
            <div class="preview-item" v-if="certificationResult.businessLicense">
              <h4>营业执照</h4>
              <template v-if="isPdfFile(certificationResult.businessLicense)">
                <iframe
                  :src="certificationResult.businessLicense"
                  style="width: 100%; height: 400px; border: none;"
                ></iframe>
              </template>
              <el-image
                v-else
                :src="certificationResult.businessLicense"
                fit="cover"
                :preview-src-list="[certificationResult.businessLicense]"
              ></el-image>
            </div>
          </div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {applyCertification, getCertificationResult} from '@/api/auth/auth';
import Header from '@/views/auth/Header.vue';
import UploadImage from '@/components/ImageUpload/index.vue';
import {mapState} from 'vuex';
import {PurchaserRoleEnum, getPurchaserRoleList, getSupplizerRoleList} from '@/utils/roleEnum';

export default {
  name: 'StepOne',
  components: {
    Header,
    UploadImage,
  },
  computed: {
    ...mapState({
      userId: state => state.user.id,
      userName: state => state.user.name,
      userRole: state => state.user.roles
    }),
    getStatusType() {
      if (!this.certificationResult || this.certificationResult.isOk === null) return 'info';
      return this.certificationResult.isOk === 1 ? 'success' : 'danger';
    },
    getStatusText() {
      if (!this.certificationResult) return '未知';
      if (this.certificationResult.isOk === 0) return '等待审核';
      return this.certificationResult.isOk === 1 ? '已通过' : '未通过';
    },
    userType() {
      console.log('当前用户角色：', this.userRole);
      return this.userRole && this.userRole.some(role => role.includes('purchaser')) ? 'purchaser' : 'supplier';
    },
    purchaserRoleList() {
      return getPurchaserRoleList();
    },
    supplizerRoleList() {
      return getSupplizerRoleList();
    }
  },
  data() {
    return {
      currentStep: 0,
      submitting: false,
      showResult: false,
      certificationStatus: null,
      form: {
        userId: '',
        merchantName: '',
        contactName: '',
        contactPhone: '',
        address: '',
        idCardFront: null,
        idCardBack: null,
        businessLicense: null,
        roleKey: null,
      },
      rules: {
        merchantName: [
          {required: true, message: '请输入商家名称', trigger: 'blur'},
          {min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur'}
        ],
        contactName: [
          {required: true, message: '请输入联系人姓名', trigger: 'blur'}
        ],
        contactPhone: [
          {required: true, message: '请输入联系电话', trigger: 'blur'},
          {pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur'}
        ],
        address: [
          {required: true, message: '请输入商家地址', trigger: 'blur'}
        ],
        idCardFront: [
          {required: true, message: '请上传身份证正面', trigger: 'change'}
        ],
        idCardBack: [
          {required: true, message: '请上传身份证反面', trigger: 'change'}
        ],
        businessLicense: [
          {required: true, message: '请上传营业执照', trigger: 'change'}
        ],
        roleKey: [
          { required: true, message: '请选择采购商类型', trigger: 'change' }
        ],
      },
      agree: false,
      certificationResult: null,
    };
  },
  async created() {
    console.log('当前用户信息：', {
      id: this.userId,
      name: this.userName,
      vuexState: this.$store.state.user
    });

    // 初始化表单的userId
    this.form.userId = this.userId;

    // 获取之前提交的认证信息
    try {
      console.log('当前用户ID：', this.userId);
      const result = await getCertificationResult(this.userId);
      if (result.data) {
        // 填充表单数据，使用上一次提交的内容
        const {
          merchantName,
          contactName,
          contactPhone,
          address,
          idCardRight,
          idCardBack,
          businessLicense
        } = result.data;
        this.form = {
          userId: this.userId,
          merchantName: merchantName || '',
          contactName: contactName || this.userName || '',
          contactPhone: contactPhone || '',
          address: address || '',
          idCardFront: idCardRight || null,
          idCardBack: idCardBack || null,
          businessLicense: businessLicense || null,
          roleKey: result.data.roleKey || null,
        };

        // 设置认证状态提示
        if (result.data.isOk === 1) {
          this.certificationStatus = {
            type: 'success',
            title: '认证已通过',
            description: '您的商家认证已通过审核'
          };
        } else if (result.data.isOk === 0) {
          this.certificationStatus = {
            type: 'warning',
            title: '等待审核',
            description: '您的认证信息正在审核中，请耐心等待'
          };
        } else if (result.data.isOk === null) {
          this.certificationStatus = {
            type: 'error',
            title: '认证未通过',
            description: result.data.reason || '您的认证未通过，请修改信息后重新提交'
          };
        }
      }
    } catch (error) {
      console.error('获取认证信息失败', error);
      // 如果是首次认证（没有认证记录），不显示错误提示
      if (error.message !== '该用户暂无认证记录') {
        this.$message.error('获取认证信息失败：' + error.message);
      }
    }
  },
  methods: {
    goBack() {
      this.$router.push('/official');
    },
    isPdfFile(url) {
      return url && url.toLowerCase().endsWith('.pdf');
    },
    async submit() {
      this.$refs.form.validate(async (valid) => {
        if (valid && this.agree) {
          this.submitting = true;
          try {
            // 确保提交时包含用户ID和roleKey (如果是采购商)
            const submitData = {
              ...this.form,
              userId: this.userId
            };

            // 如果不是采购商，删除roleKey字段
            // if (this.userType !== 'purchaser') {
            //   delete submitData.roleKey;
            // }

            await applyCertification(submitData);
            this.$message({
              type: 'success',
              message: '认证信息提交成功，请等待审核',
              duration: 3000
            });
            this.currentStep = 1;
          } catch (error) {
            this.$message.error('提交失败: ' + error.message);
            console.error('提交失败', error);
          } finally {
            this.submitting = false;
          }
        } else {
          this.$message.error('请完善信息并同意协议');
        }
      });
    },

    async getCertificationResult() {
      try {
        const result = await getCertificationResult();
        this.certificationResult = result.data;
        this.showResult = true;
        console.log('认证记录：', this.certificationResult);
      } catch (error) {
        this.$message.error('获取认证记录失败: ' + error.message);
        console.error('获取认证记录失败', error);
      }
    },
  },
};
</script>

<style scoped>
.step-one {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.form-container {
  max-width: 900px;
  margin: 0 auto;
  padding: 0 20px;
}

.form-card {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 30px;
  margin-bottom: 40px;
}

.form-header {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
  position: relative;
}

.back-button {
  position: absolute;
  left: 0;
  font-size: 14px;
  color: #409EFF;
}

.form-title {
  flex: 1;
  text-align: center;
  font-size: 24px;
  color: #1f2f3d;
  font-weight: 600;
  margin: 0;
}

.auth-form {
  max-width: 600px;
  margin: 0 auto;
}

.upload-container {
  position: relative;
}

.upload-tip {
  margin-top: 8px;
  color: #909399;
  font-size: 12px;
}

.upload-tip i {
  margin-right: 4px;
}

.form-footer {
  max-width: 600px;
  margin: 30px auto 0;
}

.agreement {
  text-align: center;
  margin-bottom: 20px;
}

.agreement-link {
  margin: 0 4px;
}

.button-group {
  display: flex;
  justify-content: center;
  gap: 20px;
}

.submit-button, .view-button {
  width: 180px;
  height: 40px;
}

.result-dialog {
  :deep(.el-dialog__body) {
    padding: 30px;
  }
}

.result-content {
  .el-descriptions {
    margin-bottom: 30px;
  }
}

.image-preview {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-top: 20px;

  .preview-item {
    h4 {
      margin-bottom: 10px;
      color: #606266;
    }

    .el-image {
      width: 100%;
      height: 150px;
      border-radius: 4px;
      border: 1px solid #ebeef5;
    }
  }
}

.el-form-item__label {
  font-weight: 500 !important;
}

:deep(.el-input__inner) {
  height: 40px;
  line-height: 40px;
}

:deep(.el-form-item.is-required:not(.is-no-asterisk) .el-form-item__label-wrap>.el-form-item__label:before,
.el-form-item.is-required:not(.is-no-asterisk)>.el-form-item__label:before) {
  color: #f56c6c;
}

:deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: #409EFF;
  border-color: #409EFF;
}

.select-tip {
  margin-top: 8px;
  color: #909399;
  font-size: 12px;
}

.select-tip i {
  margin-right: 4px;
}
</style>
